package com.heima.skydemo.Aspect;

import com.heima.skydemo.auto.AutoFillCreate;
import com.heima.skydemo.auto.AutoFillUpdate;
import com.heima.skydemo.domin.common.BaseContest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillaspect {
    @Before("@annotation(autoFillCreate)")
    public void autoFillCreate(JoinPoint joinPoint, AutoFillCreate autoFillCreate) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof Object) {
                setFieldValues(arg, "createTime", LocalDateTime.now());//
                setFieldValues(arg, "createUser", BaseContest.getContestId());
            }
        }
    }

    @Before("@annotation(autoFillUpdate)")
    public void autoFillUpdate(JoinPoint joinPoint, AutoFillUpdate autoFillUpdate) {
        Object[] args = joinPoint.getArgs();// 获取方法参数
        for (Object arg : args) {
            if (arg instanceof Object) {
                setFieldValues(arg, "updateTime", LocalDateTime.now());
                setFieldValues(arg, "updateUser", BaseContest.getContestId());
            }
        }
    }

    private void setFieldValues(Object obj, String fieldName, Object value) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // 字段不存在或无法访问，忽略
        }
    }
}
